package com.cat.dataStructure02;

import java.util.HashMap;

/**
 * @author 曲大人的喵
 * @description https://leetcode.cn/problems/maximum-number-of-ways-to-partition-an-array/
 * @create 2025/10/25 15:14
 * @since JDK17
 */

public class Solution58 {
    public int waysToPartition(int[] nums, int k) {
        int n = nums.length, ans = 0;
        long[] prefix = new long[n + 1];
        HashMap<Integer, Integer> m1 = new HashMap<>(), m2 = new HashMap<>();
        prefix[1] = nums[0];
        for (int i = 1; i < n; i++) {
            m2.merge(nums[0], 1, Integer::sum);
            prefix[i + 1] = prefix[i] + nums[i];
        }

        for (int i = 1; i < n; i++) {
            // 前部分
            long first = prefix[i], second = prefix[n] - prefix[i];
            long diff = first - second;
            if (first != second) {
                if (m1.containsKey(k + diff) || m2.getOrDefault(k - diff, 0) > 0) {
                    ans++;
                }
            } else {
                ans++;
            }
            m1.merge(nums[i], 1, Integer::sum);
            m2.merge(nums[i], -1, Integer::sum);
        }

        return ans;
    }
}
